#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netinet/in.h>

class TcpClient{
  private:
    std::string server_ip;
    int server_port;
    int sockfd;
  public:
    TcpClient(std::string _ip, int _port):server_ip(_ip), server_port(_port), sockfd(-1)
    {}

    bool Init()
    {
        sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if(sockfd < 0){
          return false;
        }

        return true;
    }

    void Start()
    {
        sockaddr_in peer;
        memset(&peer, 0, sizeof(peer));
        peer.sin_family = AF_INET;
        peer.sin_port = htons(server_port);
        peer.sin_addr.s_addr = inet_addr(server_ip.c_str());
        
        if(connect(sockfd, (sockaddr*)&peer, sizeof(peer)) < 0){
          std::cerr << "connect error" << std::endl;
        }
        else {
          std::string ip = inet_ntoa(peer.sin_addr);
          int port = ntohs(peer.sin_port); 
          Request(ip, port);
        }
    }

    void Request(std::string ip, uint16_t port)
    {
      std::string msg;
      std::cout << "Please Enter #" << std::endl;
      while(true){
        std::cin >> msg;
        write(sockfd, msg.c_str(), msg.size());

        char buffer[1024];
        ssize_t size = read(sockfd, buffer, sizeof(buffer) - 1);
        if(size > 0){
          buffer[size] = 0;
          std::cout << "[" << ip << "]: "  << port << "-> " << buffer << std::endl;
        } 
        else if(size == 0){
          break;
        }
        else {
          std::cerr << "read error" << std::endl;
          break;
        }

      }
    }

    ~TcpClient()
    {
      if(sockfd > 0) close(sockfd);
    }

};
